﻿using System;
using System.Data;
using System.Net.Http;
using System.Reflection.Emit;
using System.Threading.Tasks;
using System.Windows.Forms;
using HtmlAgilityPack;
namespace SearchApp
{
    public partial class Form1:Form
    {
        private const int MaxSummaryLength = 200;
        public Form1()
        {
            InitializeComponent();
        }

        private async void button1_Click(object sender, EventArgs e)
        {
            string keyword = keywordTextBox.Text;
            if (string.IsNullOrEmpty(keyword))
            {
                MessageBox.Show("请输入关键字");
                return;
            }

            // 使用Task.Run创建一个后台任务
            string baiduSummary = await Task.Run(() => GetSearchSummaryFromBaidu(keyword));
            string bingSummary = await Task.Run(() => GetSearchSummaryFromBing(keyword));

            richTextBox1.Text = baiduSummary;
            richTextBox2.Text = bingSummary;
        }        

        private string GetSearchSummaryFromBing(string keyword)
        {
            string url = $"https://www.bing.com/search?q={keyword}";

            using (HttpClient client = new HttpClient())
            {
                string html = client.GetStringAsync(url).Result;
                HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
                doc.LoadHtml(html);

                var summaryNode = doc.DocumentNode.SelectSingleNode("//ol[@id='b_results']//li[@class='b_algo']//p");
                if (summaryNode != null)
                {
                    string summary = summaryNode.InnerText.Trim();
                    if (summary.Length > MaxSummaryLength)
                    {
                        summary = summary.Substring(0, MaxSummaryLength);
                    }
                    return summary;
                }
            }

            return "未能找到内容";
        }
        private string GetSearchSummaryFromBaidu(string keyword)
        {

            string url = $"https://www.baidu.com/s?wd={keyword}";

            using (HttpClient client = new HttpClient())
            {
                string html = client.GetStringAsync(url).Result;
                HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
                doc.LoadHtml(html);

                var summaryNode = doc.DocumentNode.SelectSingleNode("//div[@id='content_left']//div[@class='c-abstract']");
                if (summaryNode != null)
                {
                    string summary = summaryNode.InnerText.Trim();
                    if (summary.Length > MaxSummaryLength)
                    {
                        summary = summary.Substring(0, MaxSummaryLength);
                    }
                    return summary;
                }
            }
            return "未能找到内容";
        }


    }
}
